#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
日志管理模块
"""

import os
import logging
from logging.handlers import RotatingFileHandler


def setup_logger():
    """设置日志配置"""
    # 创建logs目录
    log_dir = './logs'
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    
    # 获取日志级别
    log_level = os.getenv('MOCK_LOG_LEVEL', 'INFO').upper()
    log_file = os.getenv('MOCK_LOG_FILE', './logs/mock_wx_api.log')
    
    # 配置根日志记录器
    logging.basicConfig(
        level=getattr(logging, log_level),
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            # 控制台处理器
            logging.StreamHandler(),
            # 文件处理器（轮转）
            RotatingFileHandler(
                log_file,
                maxBytes=10*1024*1024,  # 10MB
                backupCount=5,
                encoding='utf-8'
            )
        ]
    )
    
    # 设置Flask日志
    flask_logger = logging.getLogger('werkzeug')
    flask_logger.setLevel(logging.INFO)
    
    # 设置自定义日志格式
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    
    for handler in logging.getLogger().handlers:
        handler.setFormatter(formatter)
    
    # 记录启动日志
    logger = logging.getLogger(__name__)
    logger.info("日志系统初始化完成")
    logger.info(f"日志级别: {log_level}")
    logger.info(f"日志文件: {log_file}")


def get_logger(name: str = None) -> logging.Logger:
    """获取日志记录器"""
    return logging.getLogger(name or __name__)
